package ui

import (
	"github.com/lxn/walk"
)

type LogWriter struct {
	textEdit *walk.TextEdit
}

func NewLogWriter(textEdit *walk.TextEdit) *LogWriter {
	return &LogWriter{textEdit: textEdit}
}

func (w *LogWriter) Write(p []byte) (n int, err error) {
	// 在UI线程中更新文本
	w.textEdit.Synchronize(func() {
		text := w.textEdit.Text()
		// 如果文本太长，清除一半
		if len(text) > 50000 {
			text = text[len(text)/2:]
		}
		w.textEdit.SetText(text + string(p))
		// 滚动到底部 - 通过设置光标位置实现
		w.textEdit.SetTextSelection(len(w.textEdit.Text()), len(w.textEdit.Text()))
	})
	return len(p), nil
}
